<template>
  <div>
    <!-- 合同风险识别表 -->
    <a-form-model ref="ruleForm" class="table-form" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editable ? rules : {}">
      <a-spin :spinning="loading">
        <!-- 表单 -->
        <a-card>
          <title-name title="合同风险识别表"></title-name>
    
          <a-table bordered :data-source="dataList" :columns="columns" rowKey="stringId" :scroll="{ x: 1800 }" :pagination="false">
            <template v-for="(item, index) in editableKey" :slot="item" slot-scope="text, record, index">
              <div v-if="editable" :key="item" class="requiredFormItem" :class="cellClass(record, item)">
                <a-select v-if="item == 'levelRiskType'" v-model="record[item]" @change="handleChange(item, record, $event)">
                  <!-- 风险级别type(0:红色/1：黄色/2:蓝色) -->
                  <a-select-option :value="0"> 红色 </a-select-option>
                  <a-select-option :value="1"> 黄色 </a-select-option>
                  <a-select-option :value="2"> 蓝色 </a-select-option>
                </a-select>
                
                <!-- <SelectPersonByProject
                  v-else-if="item == 'chargePersonIds'"
                  placeholder="请选择"
                  :projectId="baseFormInfo.projectId"
                  mode="multiple"
                  v-model="record[item]"
                  :currentLabel.sync="record['chargePersonNamesList']"
                ></SelectPersonByProject> -->
                <ASelectOrgPeople
                  v-else-if="item == 'chargePersonIds'"
                  placeholder="请选择"
                  :init="false"
                  mode="multiple"
                  :form="baseFormInfo"
                  key-value="projectOrgId"
                  option-key="userId"
                  v-model="record[item]"
                  @onSelectChange="(e) => record['chargePersonNamesList'] = e.map(v => v.name)"
                ></ASelectOrgPeople>
                <a-date-picker 
                  v-else-if="item == 'startTime' || item == 'endTime'"
                  @change="handleChange(item, record, $event)"
                  v-model="record[item]"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  placeholder='请选择'
                />
                <BaseInput v-else v-model="record[item]" @change="handleChange(item, record, $event)" :maxLength="300"/>
                <!-- <a-input v-else :class="validate && !record[item] ? 'validate_err' : ''" v-model="record[item]" @change="handleChange(item, record, $event)"  :maxLength="300" placeholder='请输入'/> -->
              </div>
              <template v-else>
                <span v-if="item == 'levelRiskType'">{{['红色', '黄色' ,'蓝色'][record.levelRiskType]}}</span>
                <span v-else-if="item == 'chargePersonIds'">{{ record.chargePersonNames }}</span>
                <span v-else>{{record[item]}}</span>
              </template>
            </template>
            
            <template slot="action" slot-scope="text, record, index">
              <a-popconfirm v-if="editable && index !== 0" title="确定要删除?" @confirm="() => handleDel(record, index)">
                <a>删除</a>
              </a-popconfirm>
            </template>
          </a-table>
          
          <a-button type="primary" class="mt12" :disabled="!editable" icon="plus" @click="handleManage"> 增行 </a-button>
        </a-card>
      </a-spin>
    </a-form-model>
  </div>
</template>
<script>
import { getList, update } from '@/api/projectManagementPlanning/contractRiskIdentification'
// import SelectPersonByProject from '@/components/Select/SelectPersonByProject.vue'
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople.vue'
import { getGuid } from '../../projectPlanningTaskList/config.js'
export default {
  name: 'ContractRiskIdentification' + Date.now(),
  components: {
    // SelectPersonByProject,
    ASelectOrgPeople
  },
  props: {
    baseFormInfo: {
      type: Object,
      default: () => {}
    },
  },
  data() {
    return {
      loading: false, // 加载控件
      validate: false,
      form: {
        mainConfidentialityMeasures: '',
        detailList: []
      },
      rules: {
        mainConfidentialityMeasures: [{ required: true, message: '请输入主要保密措施', trigger: 'blur' }],
      }, // 校验规则
      dataList: [],
      editableKey: [
        'contractTermNo',
        'content',
        'paraphrase',
        'levelRiskType',
        'solutions',
        'desiredEffect',
        'chargePersonIds',
        'startTime',
        'endTime',
      ]
    }
  },
  computed: {
    cellClass() {
      return (record, item) => {
        if (this.validate && (record[item] === undefined || record[item] === null || record[item] === '')) {
          return 'validate_err'
        } else {
          return ''
        }
      }
    },
    columns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          customRender(text, record, index) {
            return index + 1;
          }
        },
        {
          title: '合同条款号',
          dataIndex: 'contractTermNo',
          scopedSlots: { customRender: 'contractTermNo' },
        },
        {
          title: '内容',
          dataIndex: 'content',
          scopedSlots: { customRender: 'content' },
        },
        {
          title: '释义',
          dataIndex: 'paraphrase',
          scopedSlots: { customRender: 'paraphrase' },
        },
        {
          title: '风险级别',
          dataIndex: 'levelRiskType',
          width: 200,
          scopedSlots: { customRender: 'levelRiskType' },
        },
        {
          title: '应对措施',
          dataIndex: 'solutions',
          scopedSlots: { customRender: 'solutions' },
        },
        {
          title: '预期效果',
          dataIndex: 'desiredEffect',
          width: 200,
          scopedSlots: { customRender: 'desiredEffect' },
        },
        {
          title: '责任人',
          dataIndex: 'chargePersonIds',
          width: 200,
          scopedSlots: { customRender: 'chargePersonIds' },
        },
        {
          title: '开展时间',
          children: [
            {
              title: '开始',
              dataIndex: 'startTime',
              width: 200,
              scopedSlots: { customRender: 'startTime' },
            },
            {
              title: '完成',
              dataIndex: 'endTime',
              width: 200,
              scopedSlots: { customRender: 'endTime' },
            }
          ]
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          scopedSlots: { customRender: 'action' }
        }
      ]
    },
    pageType() {
      return this.$route.query.pageType
    },
    editable() {
      return this.$route.query.editModel == 1
    },
    planId() {
      return this.$route.query.id
    }
  },
  mounted() {
    console.log(this.baseFormInfo)
    this.getListData()
  },
  methods: {
    getListData() {
      let param = {
        isNew: this.$route.query.version ? 1 : 0,
        planId: this.planId,
      }
      if (this.$route.query.version) {
        param.version = 'V' + this.$route.query.version
      }
      getList(param).then((res) => {
        console.log(res.data)
        if (res.code == 200 || res.code == 0) {
          this.dataList = res.data
        }
      })
    },
    handleManage() {
      this.dataList.push({
        stringId: getGuid(),
        contractTermNo: '',
        content: '',
        paraphrase: '',
        levelRiskType: undefined,
        solutions: '',
        desiredEffect: '',
        chargePersonIds: [],
        startTime: '',
        endTime: '',
      })
    },
    handleDel(record, index) {
      let idx = this.dataList.findIndex(e => e.stringId == record.stringId)
      this.dataList.splice(idx, 1)
    },
    handleChange(key, record, e) {
      this.dataList = this.dataList.map((item, index) => {
        if (item.stringId == record.stringId) {
          if (key==='levelRiskType' || key==='startTime' || key==='endTime') {
            item[key] = e
          } else {
            item[key] = e.target.value
          }
        }
        return item
      })
    },
    ContractRiskIdentificationSubmit(e) {
      // this.validate = true
      let _this = this
      let flag = this.validateForm()
      if (!flag) {
        this.$warning({
          title: '温馨提示',
          content: '请将数据填写完整',
          okText: '确定'
        });
        return
      }
      this.$confirm({
        okText: '确认',
        okType: 'warning',
        cancelText: '取消',
        title: '提交?',
        content: `请确认是否要提交？`,
        onOk() {
          _this.submitForm(1)
        },
        onCancel() {
        },
      })
    },
    submitForm(type) {
      let param = { 
        identificationList: this.dataList,
        isChange: this.pageType == 'change' ? 0 : 1, // 是变更还是编辑按钮（ 0：变更|1：编辑）
        isSubmit: type, // 按钮（ 0：保存草稿按钮|1：提交按钮）编辑使用
        planId: this.planId,
        version: this.dataList[0].version
      };
      return update(param).then((res) => {
        if (res.code == 200 || res.code == 0) {
          let msg = type == 1 ? '提交' : '保存'
          this.$message.success(`${msg}成功！`);
          this.$close();
        }
      })
    },
    validateForm() {
      let flag = true
      if (this.dataList == 0) {
        this.$warning({
          title: '温馨提示',
          content: '请至少填写一行数据',
          okText: '确定'
        });
        return false
      }
      this.dataList.forEach((sub, idx) => {
        this.editableKey.map((e, i) => {
          if (e == 'chargePersonIds' && (!sub[e] || sub[e].length == 0)) {
            flag = false
          } else if (sub[e] === '' || sub[e] == undefined || sub[e] == null) {
            flag = false
          }
        })
      })
      return flag
    },
    ContractRiskIdentificationSaveDrafts(e) {
      // this.validate = false
      this.submitForm(0)
    },
  }
}
</script>
<style lang="less" scoped>
  /deep/ .requiredFormItem.validate_err .ant-input:not([disabled]),
  /deep/ .requiredFormItem.validate_err .ant-time-picker-input,
  /deep/ .requiredFormItem.validate_err .ant-select:not(.ant-select-disabled) .ant-select-selection,
  /deep/ .requiredFormItem.validate_err .ant-calendar-picker-input,
  /deep/ .requiredFormItem.validate_err .ant-input-number-input,
  /deep/ .requiredFormItem.validate_err .ant-cascader-picker {
    border-color: #f5222d;
  }
</style>
